package cn.py.boot_lua.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class UserDataFetcher {
    private final int pageSize = 10; // 每页大小

    // 获取总记录数
    private int getTotalCount() {
        return 101;
        //  SELECT COUNT(*) FROM ai_music_style
    }

    // 使用 CompletableFuture 的现代方式
    public List<String> fetchAllDataWithCompletableFuture() {
        int totalCount = getTotalCount();
        int totalPages = (totalCount + pageSize - 1) / pageSize;
        ExecutorService executor = Executors.newFixedThreadPool(2);  // 线程数

        List<CompletableFuture<List<String>>> futures = IntStream.range(0, totalPages)
                .mapToObj(page -> CompletableFuture.supplyAsync(() -> {
                    int offset = page * pageSize;
                    System.out.println("CompletableFuture - 线程 " + Thread.currentThread().getName() +
                            " 处理第 " + (page + 1) + " 页");
                    return fetchDataPage(offset, pageSize);
                }, executor))
                .collect(Collectors.toList());

        // 合并所有结果
        List<String> allData = futures.stream()
                .map(CompletableFuture::join)
                .flatMap(List::stream)
                .collect(Collectors.toList());

        executor.shutdown();
        System.out.println("CompletableFuture 方式完成，共 " + allData.size() + " 条");
        return allData;
    }

    // 分页查询方法-+-
    private List<String> fetchDataPage(int offset, int limit) {
        try {
            List<String> musicStyleList = new ArrayList<>();
            // List<String> musicStyleList = aiMusicStyleMapper.selectByPage(offset, limit);
            // List<AiMusicStyle> selectByPage(@Param("offset") Integer offset, @Param("limit") Integer limit);  // mapper
            // SELECT * FROM ai_music_style ORDER BY id LIMIT #{offset}, #{limit} // xml
            System.out.println(offset+" 获取到的数据: " + musicStyleList);
            return musicStyleList;
        } catch (Exception e) {
            System.err.println("查询失败，offset=" + offset + ", error: " + e.getMessage());
            return Collections.emptyList();
        }
    }


}
